package com.go8.admin.goods.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.go8.common.service.ServiceResponse;
import com.go8.common.util.UUIDUtils;

@RestController
@RequestMapping("/file")
public class FileController {
	private static final Logger log = LoggerFactory.getLogger(FileController.class);
	
	@PostMapping("/upload")
	public Object upload(MultipartFile file,HttpServletRequest request) {
		try {
			String ext = FilenameUtils.getExtension(file.getOriginalFilename());
			//生成随机文件名称
			String filename = UUIDUtils.getUUID();
			log.info(filename);

	        String filepath = "c:/go8/images/";
	        new File(filepath).mkdirs();
	        filepath = filepath+filename+"."+ext;
	        log.info(filepath);
	        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filepath));
	        
			Map<String,String> map = new HashMap<>();
			map.put("url", "/images/"+filename+"."+ext);
			map.put("path", filepath);
			return ServiceResponse.ok(map);
		} catch (Exception e) {
			e.printStackTrace();
			return ServiceResponse.error();
		}
	}

	@DeleteMapping()
	public Object delete(String path) {
		try {
			//删除图片要用io;
			//首先拿到文件路径，创建一个文件（抽象的概念），然后选择工具，commons-io;
			FileUtils.forceDelete(new File(path));
			return ServiceResponse.ok();
		} catch (Exception e) {
			e.printStackTrace();
			return ServiceResponse.error();
		}
	}
}
